var models = require("../models");
var persist = require("persist");

exports.index = function(req, res, next){
  persist.connect(function(err, conn) {
    if(err) { next(err); return; }

    conn.chain({posts: models.Post.include(["category"]).include(["keywords"]).all}, function(err, results) {
      if(err) {
        next(err); return; 
      }

      var posts = results.posts;

      res.render('blog.jade', {
        locals: {
          title: 'Blog',
          posts: posts
        }
      })
    })
  })
};

exports.post = function(req, res, next){
  var id = req.params.id;
  if(!id) { throw new Error("'id' is required."); }

  persist.connect(function(err, conn) {
    if(err) { next(err); return; }

    var queries = {
      posts: models.Post.include(["category"]).include(["keywords"]).where('id=?', id).all
    };

    conn.chain(queries, function(err, results) {
      if(err) { next(err); return; }

      var post = results.posts[0];

      res.render('post.jade', {
        locals: {
          title: post.title,
          post: post
        }
      });
    });
  });
};
